package com.vfa.vocaburay;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import com.vfa.data.Question;
import com.vfa.test.QuestionData;


import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


public class ImportQuestionFileCSV extends BaseImportFile{
	private QuestionData questiondata;
	@Override
	protected void DoImport(String filename) {
		// TODO Auto-generated method stub
		new DoBackgroundImportFile().execute(filename);
	}

@Override
protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	questiondata = new QuestionData(this);
}
private class DoBackgroundImportFile extends AsyncTask<String, int[], Long>{
		int numOfRecordSuccess = 0;
		int numOfRecordSkip = 0;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			//showDialog(DIALOG_IMPORT_PROGRESS);
			isImporting = true;
			mProgressbarImportFile.setProgress(0);
			mTVStatus.setText("Importing...");
		}

		@Override
		protected void onPostExecute(Long result) {
			// TODO Auto-generated method stub
			//super.onPostExecute(result);
			isImporting = false;
			Log.d("Import file","finished import");
			mProgressbarImportFile.setProgress(100);
			mProgressbarImportFile.setVisibility(View.GONE);
			//mTVStatus.setVisibility(View.INVISIBLE);
			if(numOfRecordSuccess >0)
				isImportSuccess = true;
				
			if(isImportSuccess )
			{
				setResult(RESULT_OK);
			}
			else
			{
				setResult(RESULT_CANCELED);
			}
			//mProgressDialog.setProgress(100);
			//removeDialog(DIALOG_IMPORT_PROGRESS);
			//dismissDialog(DIALOG_IMPORT_PROGRESS);
			Toast.makeText(getBaseContext(), "finished Import", Toast.LENGTH_SHORT).show();
//			Intent intent = new Intent(ImportFileCSV.this, vfaMain.class);
//			startActivity(intent);
			//ImportFileCSV.this.finish();
		}

		@Override
		protected void onProgressUpdate(int[]... values) {
			// TODO Auto-generated method stub
			Log.d("ANDRp_ASYN",""+values[0]);
			//mProgressDialog.setProgress(values[0]);
			mProgressbarImportFile.setProgress(values[0][0]);
			mTVStatus.setText("Imported "+ values[0][1] + " words, skip "+ values[0][2]  + " ("+((values[0][0] <100) ? values[0][0]:100)+"%)");
		}

		@Override
		protected Long doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				readFile(params[0], "English");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		private String[] processString(String line) {
			//bo ki tu utf8 neu co
			if(line.length() >0)
			{
				int i = line.charAt(0);
				if(i == 65279)
					line = line.substring(1);
			}
			
			ArrayList<String> result = new ArrayList<String>();
			String[] data = line.split(",");
			for (int i = 0; i < data.length; i++) {
				String temp = data[i].trim();
				if (laDauNhayBatDau(temp)) {
					while (!laDauNhayKetThuc(temp)) {
						if (i + 1 < data.length) {
							temp = temp + "," + data[i + 1];
							i++;
						} else {
							break;
						}

					}
					////sau khi noi xong bo dau nhau dau, dau nhay cuoi
					temp = temp.substring(1,temp.length()-1);
					temp = temp.replace("\"\"", "\"");
				}
				if(temp!="")
					result.add(temp);
			}
			String[] rs = new String[result.size()];
			for (int i = 0; i < result.size(); i++) {
				rs[i] = result.get(i);
			}
			return rs;

		}
		boolean laDauNhayKetThuc(String str)
		{
			
			if(str ==null ||str == "")
				return false;
			str = str.trim();
			if(str.endsWith("\""))
			{
				int soDauNhayCuoi =0;
				for(int i = str.length() -1;i >=0;i--)
				{
					if(str.charAt(i)== '"')
						soDauNhayCuoi++;
					else
						break;
				}
				if(soDauNhayCuoi%2==0)
					return false;
				return true;		
			}
			else{
				return false;
			}
		}
		boolean laDauNhayBatDau(String str)
		{
			
			if(str ==null ||str == "")
				return false;
			str = str.trim();
			int soDauNhauDau =0;
			for(int i = 0;i < str.length();i++)
			{
				if(str.charAt(i)== '"')
					soDauNhauDau++;
				else
					break;
			}
			if(soDauNhauDau%2==0)
				return false;
			return true;		
		}
		private void readFile(String filepath, String language) throws IOException {
			Log.e("cannc", language);
			try {
				File file = new File(filepath);
				FileInputStream fileIS = new FileInputStream(file);
				final BufferedReader buf = new BufferedReader(
						new InputStreamReader(fileIS,"UTF-8"));
				String readString;
				long totalSize = fileIS.getChannel().size();
				long currentPos = 0;
				numOfRecordSuccess = 0;
				while ((readString = buf.readLine()) != null) {

					// Log.d("cannc", readString);
					String[] datas = processString(readString);
					if(datas.length <2)
					{
						continue;
					}
					int matchSentence = 0 ;
					try {
						matchSentence = Integer.parseInt(datas[1].trim());
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						numOfRecordSkip++;
						continue;
					}
					

					String strQuestion = datas[0].trim();
					strQuestion = strQuestion.replaceAll("[']", "''");
					// check exist?
					boolean isSuccess = false;
					if(questiondata.checkInDatabase(strQuestion)!=1){
						questiondata.InsertQuestion(strQuestion);
						numOfRecordSuccess++;
						isSuccess = true;
					}
					else{
						numOfRecordSkip++;
						//continue;
						
					}
					if (isSuccess) {
						System.out.println("insert Q");
						questiondata.returnIdQuestion(strQuestion);
						System.out.println("return Q");
						// insert answer
						for (int i = 2; i < datas.length; i++) {
							String strAnswer = datas[i].trim();
							if (i - 2 + 1 == matchSentence) {
								questiondata.InsertAnswer(strAnswer, 1);
							} else {
								questiondata.InsertAnswer(strAnswer, 0);
							}
						}
					}
//					try {
//						Thread.sleep(100);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
					currentPos+= readString.getBytes().length +2;//ki tu xuong dong
					Log.d("ImportProcess", ""+ currentPos +"/" + totalSize);
					//mProgressDialog.setProgress((int)((currentPos*100)/totalSize));
					publishProgress(new int[]{(int)((currentPos*100)/totalSize),numOfRecordSuccess,numOfRecordSkip});

				}
				buf.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		


	}

}
